package win.itshen.cloud.shiro.modules.admin.controller;

import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.LockedAccountException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import win.itshen.cloud.shiro.common.controller.SuperController;
import win.itshen.cloud.shiro.modules.admin.entity.User;

/**
 * @author: stephen.shen
 * @create: 2019-05-23 10:24
 */
@Slf4j
@Controller
public class LoginController extends SuperController {

    @GetMapping("/login")
    public String login() {
        return "login";
    }

    @PostMapping("/login")
    public String login(String username, String password, String captchaCode, boolean rememberMe, Model model ){

        //1、检验验证码
//        if (captchaCode != null) {
//            String inputCode = request.getParameter("captchaCode");
//            String captchaSession = (String) session.getAttribute(Constants.KAPTCHA_SESSION_KEY);
//            if (!Objects.equals(inputCode, captchaSession)) {
//                log.info("验证码错误，用户输入：{}, 正确验证码：{}", inputCode, captchaSession);
//                model.addAttribute("msg", "验证码不正确!");
//                //CsrfTokenUtil.refreshToken(request);
//                return "login";
//            }
//        }
        //2、验证用户名和密码
        Subject subject = SecurityUtils.getSubject();
        UsernamePasswordToken usernamePasswordToken = new UsernamePasswordToken(username, password,rememberMe);
        String msg = "";
        try {
            subject.login(usernamePasswordToken);
            return "redirect:/";
        } catch (UnknownAccountException e) {
            log.info("UnknownAccountException -- > 账号不存在：");
            msg = "账号不存在!";
        } catch (IncorrectCredentialsException e) {
            log.info("IncorrectCredentialsException -- > 密码不正确：");
            msg = "密码不正确!";
        } catch (LockedAccountException e) {
            log.info("LockedAccountException -- > 账号被锁定");
            msg = "账号被锁定!";
        } catch (Exception e) {
            log.info(e.getMessage());
        }
        model.addAttribute("msg", msg);
        //CsrfTokenUtil.refreshToken(request);
        return "login";
    }

    @RequestMapping("/")
    public String redirectIndex() {
        return "redirect:/index";
    }

    @RequestMapping("/index")
    public String index(Model model) {
        User user = (User) SecurityUtils.getSubject().getPrincipal();
        model.addAttribute("user", user);
        return "index";
    }


}
